<script setup lang="ts">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch } from 'vue'
import { DepartmentUserItem } from '@/api/department/types'
import { useValidator } from '@/hooks/web/useValidator'
import { FormItemRule } from 'element-plus'

const { required, minlength } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<DepartmentUserItem>,
    default: () => undefined
  }
})
const validatePass2 = (): FormItemRule => {
  return {
    validator: (_, val, callback) => {
      getFormData().then((res) => {
        if (val !== res.newPassword) {
          callback(new Error('两次输入的密码不一致!'))
        } else {
          callback()
        }
      })
    }
  }
}
const form = reactive({
  newPassword: '',
  conPassword: '',
  id: ''
})
const rules = reactive({
  newPassword: [required(), minlength(6)],
  conPassword: [required(), minlength(6), validatePass2()]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    const params = {
      userId: form.id,
      password: formData.newPassword
    }
    return params
  }
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    form.id = currentRow.id
    console.log(form)
    setValues(form)
  },
  {
    deep: true,
    immediate: true
  }
)
const formSchema = reactive<FormSchema[]>([
  {
    field: 'newPassword',
    component: 'Input',
    label: '新密码',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: '请输入新密码',
      showPassword: true,
      minlength: 6
    }
  },
  {
    field: 'conPassword',
    component: 'Input',
    label: '确认密码',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: '请输入新密码',
      showPassword: true,
      minlength: 6
    }
  }
])

defineExpose({
  submit
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
</template>
